package com.frost.blog.controller;

import com.frost.blog.model.BlogInfo;
import com.frost.blog.model.Result;
import com.frost.blog.model.UserInfo;
import com.frost.blog.service.BlogService;
import com.frost.blog.service.UserService;
import com.frost.blog.util.JWTUtils;
import com.frost.blog.util.SecurityUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.frost.blog.constants.Constant.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        // 1. 对参数进行校验
        // 2. 对密码进行校验
        // 3. 如果校验成功生成token
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户或者密码不能为空");
        }
        UserInfo userInfo = userService.queryUserByName(userName);
        if (userInfo == null || userInfo.getId() <= 0) {
            return Result.fail("用户不存在");
        }
        // 密码校验
//        if (!userInfo.getPassword().equals(password)) {
//            return Result.fail("用户或者密码不正确");
//        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())) {
            return Result.fail("用户或者密码不正确");
        }
        System.out.println("密码正确");
        // 密码正确,生成token
        Map<String, Object> claim = new HashMap<>();
        claim.put(USER_CLAIM_ID, userInfo.getId());
        claim.put(USER_CLAIM_NAME, userInfo.getUserName());

        return Result.success(JWTUtils.getToken(claim));
    }

    /**
     * 获取当前登录用户的信息
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        // 获取token
        // 从token中获取用户Id
        String userToken = request.getHeader(USER_TOKEN);
        Integer userId = JWTUtils.getUserIdFromToken(userToken);
        // 根据id获取用户信息
        if (userId == null || userId <= 0) {
            return null;
        }
        UserInfo userInfo = userService.queryUserById(userId);
        userInfo.setPassword("");
        return userInfo;
    }

    /**
     * 根据博客id获取作者的信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {

        if (blogId == null || blogId <= 0) {
            return null;
        }
        UserInfo authorInfo = userService.queryAuthorInfoByBlogId(blogId);
        authorInfo.setPassword("");
        return authorInfo;
    }
}
